<template>
  <div class="">
    <audio id="audio" @ended="playAudioEnd" class="c-pf c-p-l-100"></audio>
    <div class="c-bg-sgray c-br20  c-mt20 c-ph24 c-pv24">
      <div class="c-fs28 c-fc-xblack c-fw600">
        我的答案
      </div>
      <!-- 文字回答 -->
      <div class="modal-textarea c-bd-b1 c-pb20 c-mb24">
        <textarea @focus="inputFocus" @blur="inputBlur" v-model="answerText" maxlength="10000" class="needsclick c-lh40 c-fc-xblack" placeholder="请输入答案内容"></textarea>
        <div class="c-w100 c-lh c-pt20 c-textAlign-r c-fs18  c-fc-sgray">{{answerText.length}}/10000</div>
      </div>
      <!-- 语音回答 -->
      <div class="c-flex-row c-flexw-wrap" v-if="uploadAudioList.length > 0">
        <div @click.stop="clickPlayAudio(item.url)" v-for="(item,index) in uploadAudioList" :key="index" class="c-ww150 c-hh60 c-br30 theme-bg-10 c-pl24 c-pr10 c-p c-flex-row c-aligni-center c-mb30" :class="(index+1)%3==0?'':'c-mr22'" >
          <div class="box c-ww32">
            <div class="wifi-symbol">
              <div class="wifi-circle first theme-bd2"></div>
              <div class="wifi-circle second theme-bd2" :class="playAduioSrc == item.url?'seconAnimation':''"></div>
              <div class="wifi-circle third theme-bd2" :class="playAduioSrc == item.url?'thirdAnimation':''"></div>
            </div>
          </div>
          <div class="c-fs20 theme-fc">{{changeTimeStr(item.time)}}</div>
          <i @click.stop="clickDelAudio(index)" class="iconfont c-fs14 c-fc-white del-img">&#xeca0;</i>
        </div>
      </div>
      <!-- 视频回答 -->
      <div class="c-flex-row c-flexw-wrap" v-if="uploadVideoList.length > 0">
        <div v-for="(item,index) in uploadVideoList" :key="index">
          <div @click.stop="clickShowVideo(item.realUrl || item.videoMp4)" class="c-p c-ww150 c-hh100 c-mb30" :class="(index+1)%3==0?'':'c-mr22'" >
            <img class="c-w100 c-h c-br20" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/clockIn/video-bg1.png" alt="" />
            <i @click.stop="clickDelVideo(index)" class="iconfont c-fs14 c-fc-white del-img">&#xeca0;</i>
          </div>
        </div>
      </div>
      <!-- 图片回答 -->
      <div class="c-flexw-wrap c-flex-row" v-if="uploadImgList.length > 0">
        <div v-for="(item,index) in uploadImgList" :key="index" class="c-ww150 c-hh150 c-mb30 c-flex-row c-flex-center c-p " :class="(index+1)%3==0?'':'c-mr22'" >
          <div @click="delUploadImage(index)" class="iconfont c-fs14 c-fc-white del-img">&#xeca0;</div>
          <img @click="clickPreviewImage(item.content)" class="c-ww150 c-hh150 c-br20" :src="$addXossFilter(item.url)" alt="" />
        </div>
      </div>
      <!-- 文档回答 -->
      <div v-if="uploadOfficeList.length > 0">
        <div @click="clickPrevireOffice(index)" v-for="(item,index) in uploadOfficeList" :key="index" class="c-p c-pv20 c-ph20 c-mb20 c-bg-F6F7F9 c-br20">
          <div @click="delUploadOffice(index)" class="iconfont c-fs14 c-fc-white del-img">&#xeca0;</div>
          <div class="c-flex-row c-aligni-center">
            <div>
              <img class="c-ww64 c-hh64 c-br20" :src="$addXossFilter(officeIconImg[item.type])" alt="" />
            </div>
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2 c-ml16 c-ww410">
              {{item.name}}
            </div>
          </div>
        </div>
      </div>
      <!-- 选择回答类型 -->
      <div class="c-flex-row c-justify-sb">
        <div class="c-flex-row c-fc-sblack">
          <div @click="clickAddAudio" class="c-mr60">
            <i class="iconfont c-fs32">&#xe75b;</i>
          </div>
          <!-- <div @click="clickUploadVideo" class="needsclick c-mr60">
            <i class="needsclick iconfont c-fs32">&#xe75d;</i>
          </div> -->
          <div class="c-p c-mr60">
            <div @click="clickAnswerPic" class="c-w100">
              <i class="iconfont c-fs32">&#xe75e;</i>
            </div>
            <input class="c-pa c-opacity0 c-p-t0 c-p-l0 c-w100 c-hh40 c-fs10" v-if="!isWeiXin" ref="uploadImg" name="file" type="file" accept="image/*" @change="clickAnswerPic($event)" />
          </div>
        </div>
      </div>
    </div>
    <input class="hide c-cursor-p needsclick" id="myUpload" type="file" accept="video/*" @change='onInputChange($event)' />
    <clock-audio-record :enableLongAudio='0' :showAudioRecordModal='showAudioRecordModal' @closeAudioRecordModal='closeAudioRecordModal' @uploadAudioSuccess='uploadAudioSuccess'></clock-audio-record>
    <!-- 视频播放器 -->
    <video-popup :showVideo="showVideo" @clickCloseVideo="clickCloseVideo" :videoSrc="currentVideoObj.videoSrc" :m3u8Url="currentVideoObj.m3u8Url"></video-popup>
    <my-loading :showLoading="showProgress" :text="uploadProgress"></my-loading>
  </div>
</template>

<script>
import TcVod from "vod-js-sdk-v6";
import clockAudioRecord from "@/components/templates/clockIn/clockAudioRecord.vue";
import videoPopup from "@/components/templates/common/videoPopup.vue";
import myLoading from "@/plugin/loading/loading.vue";
import { utilJs, wxUtilJs } from "@/utils/common.js";
let serverIdImgArr = []; //上传图片的serverID
let inputScrollTop = 0;
let uploader = null;
let imgData = {};
export default {
  name: "SimpleQue",
  components: {
    myLoading,
    clockAudioRecord,
    videoPopup,
  },
  props: {
    questionInfo: {
      type: Object,
      default: null
    },
    number: {
      type: Number,
      default: 0
    },
    mId: {
      type: Number,
      default: 0
    },
    answerText: {
      type: String,
      default: ''
    },
    uploadImgList: {
      type:Array,
      default:[]
    }, //需要上传的图片
    uploadAudioList: {
      type:Array,
      default:[]
    }, //需要上传的音频
    uploadVideoList: {
      type:Array,
      default:[]
    }, //需要上传的视频
    uploadOfficeList: {
      type:Array,
      default:[]
    }, //需要上传的文档
  },
  beforeRouteLeave(to, from, next) {
  },
  data() {
    return {
      userHeadImg: localStorage.getItem("userHeadImg"),
      showChooseOffice: false,
      cfg: JSON.parse(localStorage.getItem("cfg")),
      theme: localStorage.getItem("colorName")
        ? localStorage.getItem("colorName")
        : "mb5_default",
      showDesc: false, //显示课程
      showVideo: false, //显示视频
      showProgress: false,
      uploadProgress: '0',
      tutorPhone: "", //监护人电话
      playAduioSrc: "", //播放音频的src
      recordStatus: "START", //录音状态
      recordTime: 0, //录音时间
      isPlayTest: false, //是否试听播放
      showAudioRecordModal: false, //显示录音控制器
      uploadOfficeList: [], //需要上传的文档
      baseSetting: {},
      ttId: "", //营期ID
      tpId: "", //环节ID
      tlId: "", //课时ID
      isWeiXin: true,
      currentVideoObj: {},
      answerPopupShow: false,
      thwId:0,
    };
  },
  watch:{
    answerText(val) {
      this.pusDate()
    }
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {

  },
  methods: {
    //获取得到的文件file
    onInputChange(e) {
      let inputFile = e.target.files[0];
      if (inputFile && inputFile.size > 1024 * 1024 * 1024) {
        this.$showCjToast({
          text: "视频文件大小不能超过1G",
          type: "warn",
          time: 1000
        });
        return false;
      }
      if (inputFile) {
        this.uploadVideoToTencent(inputFile);
      }
    },
    uploadVideoToTencent(inputFile) {
      let that = this;
      this.showProgress = true;
      const tcVod = new TcVod({
        // eslint-disable-line
        getSignature: utilJs.getVideoSign
      });
      uploader = tcVod.upload({
        mediaFile: inputFile // 媒体文件（视频或音频或图片），类型为 File
      });
      uploader.on("media_progress", function (info) {
        that.uploadProgress = `上传进度:${Math.floor(info.percent * 100)}%`;
      });
      uploader
        .done()
        .then(function (result) {
          that.showProgress = false;
          let videoInfo = {
            url: result.fileId,
            realUrl: result.video.url
          };
          that.uploadVideoList.push(videoInfo);
          let data = {
            videoId: result.fileId,
            videoMp4: result.video.url,
            videoName: inputFile.name
          };
          that.videoFirstSave(data);
          that.uploadProgress = '0';
          document.getElementById("myUpload").value = null;
        })
        .catch((err) => {
          that.showProgress = false;
          that.$showCjToast({
            text: "上传失败，请尝试重新上传",
            type: "warn",
            time: 1000
          });
          that.uploadProgress = '0';
          document.getElementById("myUpload").value = null;
          let errorData = {
            errorMsg: JSON.stringify(err),
            errorType: "UPLOAD_VIDEO_ERROR"
          };
          utilJs.reprotError(errorData);
        });
    },
    pusDate() {
      let answer = {
        answer:this.answerText,
        imgArr:this.uploadImgList,
        audioArr:this.uploadAudioList,
        videoArr:this.uploadVideoList
      }
      console.log(answer)
      this.$emit('pushAnswer', this.mId, answer, this.questionInfo.type)
    },
    //时间转换成"形式
    changeTimeStr(timeStr) {
      return utilJs.timeTmpToNsTime(timeStr)
    },
    totalTime(uploadAudioList) {
      let totalTime = 0
      for (let item in uploadAudioList) {
        totalTime = totalTime + uploadAudioList[item].time
      }
      console.log(totalTime, '77777')
      return utilJs.timeTmpToStrTime(totalTime)
    },
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
    //添加音频
    clickAddAudio() {
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
      if (utilJs.getAppVersion() > 0) {
        this.initAppRecordEvent();
        utilJs.sendDataToAppNew('record', 'appAudioStartRecord');
        return;
      }
      this.showAudioRecordModal = true;
    },
    //关闭录音弹窗
    closeAudioRecordModal(state) {
      if (state == 1) {
        this.showAudioRecordModal = false;
      }
    },
    //音频上传成功
    uploadAudioSuccess(audioContent, state) {
      if (state == 1) {
        this.showAudioRecordModal = false;
      }
      // let url = audioContent.content
      let audioItem = {
        url: audioContent.content,
        time: audioContent.time
      };
      this.uploadAudioList.push(audioItem);
      console.log(this.uploadAudioList)
      this.pusDate()
    },
    initAppRecordEvent() {
      window['cjAppAudioRecordResult'] = this.appRecordResult;
    },
    //app录音结果回调
    appRecordResult(resKey, time) {
      console.log('*******appRecordResult***', resKey, time)
      let resUrl = `https://qnoss.ckjr001.com/${resKey}`;
      let info = {
        content: resUrl,
        time:time
      }
      this.uploadAudioSuccess(info);
    },
    clickShowDesc(isShow) {
      this.showDesc = isShow;
    },

    //点击显示视频
    clickShowVideo(videoSrc, m3u8Url) {
      this.showVideo = true;
      this.currentVideoObj = {videoSrc, m3u8Url}
    },
    //点击关闭视频
    clickCloseVideo() {
      if (this.showVideo) {
        this.showVideo = false;
      }
    },
    //点击开始播放音频
    clickPlayAudio(audioUrl) {
      let audio = document.getElementById("audio");
      if (this.playAduioSrc == audioUrl) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        return;
      }
      this.playAduioSrc = audioUrl;
      console.log(this.playAduioSrc)
      if (this.playAduioSrc && this.playAduioSrc.includes("http")) {
        document.getElementById("audio").src = this.playAduioSrc;
        audio.play();
      }
    },

    //监听音频播放结束执行的内容
    playAudioEnd() {
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
    },

    // 删除音频
    clickDelAudio(index) {
      if (document.getElementById("audio")) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        document.getElementById("audio").pause();
      }
      this.uploadAudioList.splice(index, 1);
      this.pusDate()
    },

    //点击回答图片
    clickAnswerPic(event) {
      if (this.uploadImgList.length >= 9) {
        this.$showCjToast({
          text: "图片最多只能传9张",
          type: "warn",
          time: 1500
        });
        return;
      }
      if (this.isWeiXin) {
        wxUtilJs
          .chooseImage({
            count: 9, // 默认9
            sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"] // 可以指定来源是相册还是相机，默认二者都有
          })
          .then((localIds) => {
            this.$loading.show({
              text: "上传中..."
            });
            serverIdImgArr = [];
            //获取剩余能传多少张图片，若已选的图片数量大于剩余数。则只传剩余数量的图片
            let residueLength = 9 - this.uploadImgList.length;
            if (localIds.length > residueLength) {
              localIds.length = residueLength;
            }
            this.wxUploadImg(localIds, localIds.length - 1);
          });
      } else {
        utilJs.imgUpload(
          event.target.files,
          imgData,
          "clock",
          (res) => {
            let urlObj = {
              url: res
            };
            this.uploadImgList.push(urlObj);
            this.pusDate()
          },
          (fRes) => {}
        );
      }
    },

    //上传图片到微信-----IOS不能一次性传多张，只好递归传
    wxUploadImg(localIds, localIdsLength) {
      wxUtilJs
        .uploadImage(
        {
          localId: localIds[localIdsLength]
        },
          true
        )
        .then((res) => {
          serverIdImgArr.push(res);
          if (localIdsLength > 0) {
            this.wxUploadImg(localIds, --localIdsLength);
          } else {
            this.syncUploadPic(serverIdImgArr);
          }
        });
    },

    //上传图片到服务器
    syncUploadPic(serverIdArr) {
      utilJs.postMethod(
        global.apiurl + "signCard/downWxImg ",
        {
          serverId: JSON.stringify(serverIdArr),
          mediaType: 2
        },
        (res) => {
          this.$loading.hide();
          for (let key of res) {
            if (this.uploadImgList.length >= 9) {
              break;
            }
            let urlObj = {
              url: key
            };
            this.uploadImgList.push(urlObj);
            this.pusDate()
          }
        },
        (failRes) => {
          this.$loading.hide();
        }
      );
    },
    //删除上传的图片
    delUploadImage(index) {
      this.uploadImgList.splice(index, 1);
      this.pusDate()
    },

    //点击图片放大预览
    clickPreviewImage(imgUrl) {
      if (!imgUrl) {
        return;
      }
      let imgArr = [];
      for (let key of this.uploadImgList) {
        imgArr.push(key.url);
      }
      let imgData = {
        current: imgUrl, // 当前显示图片的http链接
        urls: imgArr
      }
      wxUtilJs.previewImage(imgData)
      // wxUtilJs.previewImage({
      //   current: imgUrl, // 当前显示图片的http链接
      //   urls: imgArr // 需要预览的图片http链接列表
      // });
    },

    // 删除视频
    clickDelVideo(index) {
      this.uploadVideoList.splice(index, 1);
      this.pusDate()
    },

    //点击上传视频
    clickUploadVideo() {
      if (this.uploadVideoList.length >= 9) {
        this.$showCjToast({
          text: "视频最多为9个",
          type: "warn",
          time: 1000
        });
        return
      }
      document.getElementById("myUpload").click();
    },
    //保存视频
    videoFirstSave(data) {
      utilJs.postMethod(
        global.apiurl + "signCard/videoFirstSave",
        data,
        (res) => {}
      );
    },
    //提交前校验
    checkSubmit() {
      if (
        this.answerText == "" &&
        this.uploadImgList.length == 0 &&
        this.uploadAudioList.length == 0 &&
        this.uploadVideoList.length == 0
      ) {
        this.$showCjToast({
          text: "没有提交任何内容",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.answerText.length > 10000) {
        this.$showCjToast({
          text: "字数最多为10000字",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.uploadVideoList.length > 9) {
        this.$showCjToast({
          text: "视频最多为9个",
          type: "warn",
          time: 1000
        });
        return false;
      } else {
        return true;
      }
    },
    clickDesc() {
      if (this.showDesc) {
        this.showDesc = false;
      } else {
        this.showDesc = true;
      }
    },
    initData() {
      serverIdImgArr = []; //上传图片的serverID
      this.showChooseOffice = false;
      this.showDesc = false;
      this.showVideo = false;
      this.showProgress = false;
      this.uploadProgress = '0';
      this.playAduioSrc = "";
      this.recordStatus = "START";
      this.recordTime = 0;
      this.isPlayTest = false;
      this.showAudioRecordModal = false;
      this.baseSetting = {};
      this.currentVideoObj = {};
    },
  },
  mounted() {
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = "";
    }
    this.isWeiXin = utilJs.isWeiXin() && utilJs.isMobileUserAgent();
    this.initData();
    uploader = null;
    if (document.getElementById("myUpload")) {
      document.getElementById("myUpload").value = null;
    }
    //获取阿里云签名，除了微信浏览器以外
    if (!this.isWeiXin) {
      utilJs.getAliSign(`${global.apiurl}imageSign`, (res) => {
        imgData = res;
      });
    }
    //解决ios播放没声音
    try {
      document.addEventListener(
        "WeixinJSBridgeReady",
        function () {
          document.getElementById("audio").play();
        },
        false
      );
      WeixinJSBridge.invoke("getNetworkType", {}, function (e) {
        // eslint-disable-line
        // 在这里拿到 e.err_msg, 这里面就包含了所有的网络类型
        document.getElementById("audio").play();
        console.log("WeixinJSBridgeWeixinJSBridgeWeixinJSBridgeWeixinJSBridge");
      });
    } catch (error) {
      // continue regardless of error
    }
  },
  deactivated() {
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = "";
    }
    uploader && uploader.cancel();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.submit-bg {
  color: #fff;
  font-size: .55rem;
  border-radius: .8rem;
  text-align: center;
  height: 1.2rem;
  line-height: 1.2rem;
  padding: 0 1rem;
  /* background-image: linear-gradient(90deg, #FE9901 0%, #FEB74C 100%); */
}
.input-reset {
  border: 1px solid #e5e5e5!important;
}
.modal {
  z-index: 40003!important;
}
.modal-textarea {
  padding: 0.4rem 0 0.4rem 0rem;
  width: 100%;
  height: 4.9rem;
  display: flex;
  flex-direction: column;
}

.modal-textarea textarea {
  font-size: 0.65rem;
  outline: none;
  border: none;
  width: 100%;
  height: 100%;
  background: none;
  -webkit-appearance: none;
  resize: none;
}

.modal-textarea textarea:focus {
  outline: none;
}
.del-img {
  position: absolute;
  top: 0rem;
  right: 0rem;
  width: 0.6rem;
  height: 0.6rem;
  line-height: 0.6rem;
  text-align: center;
  background: #999;
  border-radius: 50%;
  /* cursor: pointer;
  background: rgba(0, 0, 0, 0.3); */
}
.del-icon  {
  position: absolute;
  top: -0.3rem;
  right: -0.3rem;
  width: .6rem;
  height: .6rem;
  border-radius: 50%;
  background: #FF4040;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.del-icon .iconfont{
  transform: scale(0.3);
  font-size: .8rem;
  display: block;
  font-weight: bold;
}

.box-bl-r8 {
  border-bottom-left-radius: 0.2rem;
  border-bottom-right-radius: 0.2rem;
}
.vux-popup-dialog {
  background-color: #fff;
  border-radius: 10px 10px 0 0;
}
.box {
  box-sizing: border-box;
  position: relative;
}
.wifi-symbol {
  width: 1rem;
  height: 1rem;
  overflow: hidden;
  position: relative;
  transform: rotate(135deg);
  -webkit-transform-origin: center;
  transform-origin: center;
  -webkit-transform: translate3d(135deg,0,0);
  -webkit-backface-visibility: hidden;
}
.wifi-circle {
  /* border: 0.1rem solid #999999; */
  border-radius: 50%;
  overflow: hidden;
  -webkit-backface-visibility: hidden;
  position: absolute;
  -webkit-transform: translate3d(0,0,0);
}

.first {
  width: 0.1rem;
  height: 0.1rem;
  background: #cccccc;
  top: 0.9rem;
  left: 0.9rem;
}
.second {
  width: 0.5rem;
  height: 0.5rem;
  top: 0.7rem;
  left: 0.7rem;
}
.seconAnimation{
  animation: fadeInOut 1s infinite 0.2s;
}
.third {
  width: 0.8rem;
  height: 0.8rem;
  top: 0.5rem;
  left: 0.5rem;
}
.thirdAnimation{
  animation: fadeInOut 1s infinite 0.4s;
}
@keyframes fadeInOut {
    0% {
        opacity: 0; /*初始状态 透明度为0*/
    }
    100% {
        opacity: 1; /*结尾状态 透明度为1*/
    }
}
</style>
